package com.ruoyi.face.controller;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;

import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.face.domain.InoutRecord;
import com.ruoyi.face.service.IInoutRecordService;
import com.ruoyi.face.utils.ImageBase64Utils;

import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.face.domain.Face;
import com.ruoyi.face.service.IFaceService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 人脸识别测试Controller
 *
 * @author ruoyi
 * @date 2025-03-25
 */
@RestController
@RequestMapping("/face")
public class FaceController extends BaseController {
    @Autowired
    private IFaceService faceService;

    @Autowired
    private IInoutRecordService inoutRecordService;

    @Autowired
    private RemoteFileService remoteFileService;


    @Value("${tencent.cloud.secretId}")
    private String SECRET_ID;

    @Value("${tencent.cloud.secretKey}")
    private String SECRET_KEY;

    @Value("${tencent.cloud.endpoint}")
    private String ENDPOINT;

    @Value("${tencent.cloud.face.groupId}")
    private String GROUP_ID;

    @Value("${tencent.cloud.face.region}")
    private String REGION;

    @Value("${tencent.cloud.face.score}")
    private int SCORE;



    /**
     * 初始化腾讯云客户端
     */
    private IaiClient initClient() {
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(ENDPOINT);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new IaiClient(cred, REGION, clientProfile);
    }

    /**
     * 人脸比对（支持上传图片）
     */
    @PostMapping("compare")
    public AjaxResult compare(@RequestParam("imageA") MultipartFile imageA, @RequestParam("imageB") MultipartFile imageB) {
        try {
            IaiClient client = initClient();

            // 将上传的图片转换为Base64
            String base64Image1 = ImageBase64Utils.imageToBase64(imageA.getBytes());
            String base64Image2 = ImageBase64Utils.imageToBase64(imageB.getBytes());

            // 创建人脸比对请求
            CompareFaceRequest req = new CompareFaceRequest();
            req.setImageA(base64Image1);
            req.setImageB(base64Image2);

            // 发送请求并获取响应
            CompareFaceResponse resp = client.CompareFace(req);
            double score = resp.getScore();
            boolean isSamePerson = score > SCORE; // 判断是否为同一个人

            logger.info("相似度分数: {}", score);
            Map<String, Object> map = new HashMap<>();
            map.put("score", score);
            map.put("isSamePerson", isSamePerson);
            return success(map);

        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云API调用失败: {}", e.getMessage());
            return error("腾讯云API调用失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("系统异常: {}", e.getMessage(), e);
            return error("系统异常: " + e.getMessage());
        }
    }


    /**
     * 查询人脸（支持上传图片）
     */
    @PostMapping(value = "/queryFace", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult query(@RequestParam("image") MultipartFile image) {
        try {
            IaiClient client = initClient();

            // 将上传的图片转换为Base64
            String base64Image = ImageBase64Utils.imageToBase64(image.getBytes());

            // 创建请求对象
            SearchFacesRequest req = new SearchFacesRequest();
            req.setGroupIds(new String[]{GROUP_ID});
            req.setImage(base64Image);
            req.setMaxFaceNum(1L);
            req.setMaxPersonNum(1L);
            req.setNeedPersonInfo(1L); // 1L 表示 true，0L 表示 false

            // 发送请求
            SearchFacesResponse resp = client.SearchFaces(req);

            // 处理响应
            if (resp.getResults() != null && resp.getResults().length > 0) {
                Result result = resp.getResults()[0];
                if (result.getCandidates() != null && result.getCandidates().length > 0) {

                    //相似度限制
                    if (result.getCandidates()[0].getScore() < SCORE) {
//                        return ResponseDTO.fail("人脸不存在于人员库中");
                        return error("人脸不存在于人员库中");
                    }


                    logger.info("人脸存在于人员库中，人员ID: {}, 相似度: {}",
                            result.getCandidates()[0].getPersonId(),
                            result.getCandidates()[0].getScore());
//                    return new ResponseDTO(1, "人脸识别成功", result);

                    R<SysFile> r = remoteFileService.upload(image);


                    System.err.println(r.getData().getUrl());

                    InoutRecord inoutRecord = new InoutRecord();
                    inoutRecord.setCommunityId(2L);
                    Long personId = Long.parseLong(result.getCandidates()[0].getPersonId());
                    inoutRecord.setPersonId(personId);
                    inoutRecord.setInPic(r.getData().getUrl());

                    inoutRecordService.insertInoutRecord(inoutRecord);

                    return new AjaxResult(200, "人脸识别成功", result);

                } else {
                    logger.info("人脸不存在于人员库中");
//                    return ResponseDTO.fail("人脸不存在于人员库中");
                    return error("人脸不存在于人员库中");
                }
            } else {
                logger.info("未检测到人脸或人员库为空");
//                return ResponseDTO.fail("未检测到人脸或人员库为空");
                return error("未检测到人脸或人员库为空");
            }
        } catch (TencentCloudSDKException e) {
            logger.error("调用腾讯云API失败: {}", e.getMessage());
            return error("调用腾讯云API失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("发生异常: {}", e.getMessage(), e);
            return error("发生异常: " + e.getMessage());
        }
    }

    /**
     * 添加人员到人员库（支持上传图片）
     */
    @PostMapping("AddPersonToGroup")
    public AjaxResult AddPersonToGroup(@RequestParam("image") MultipartFile image,
                                       @RequestParam("personName") String personName,
                                       @RequestParam("personId") String personId) {
        try {
            IaiClient client = initClient();

            // 创建人员
            createPerson(client, GROUP_ID, personName, personId, image.getBytes());
            logger.info("创建人员成功，人员ID: {}", personId);

            // 添加人脸
            //addFaceToPerson(client, personId, image.getBytes());
            //logger.info("添加人脸成功");

            return success("添加人员成功");
        } catch (TencentCloudSDKException e) {
            logger.error("调用腾讯云API失败: {}", e.getMessage());
            return error("调用腾讯云API失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("发生异常: {}", e.getMessage(), e);
            return error("发生异常: " + e.getMessage());
        }
    }


    /**
     * 创建人员
     */
    private String createPerson(IaiClient client, String groupId, String personName, String personId, byte[] imageBytes) throws TencentCloudSDKException {
        CreatePersonRequest req = new CreatePersonRequest();
        req.setGroupId(groupId);
        req.setPersonName(personName);
        req.setPersonId(personId); // 自定义人员ID

        try {
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            req.setImage(base64Image);
        } catch (Exception e) {
            throw new TencentCloudSDKException("图片处理失败: " + e.getMessage());
        }

        CreatePersonResponse resp = client.CreatePerson(req);
        logger.info("CreatePersonResponse: {}", resp.toString());
        return req.getPersonId(); // 返回自定义的人员ID
    }

    /**
     * 添加人脸
     */
    private void addFaceToPerson(IaiClient client, String personId, byte[] imageBytes) throws Exception {
        CreateFaceRequest req = new CreateFaceRequest();
        req.setPersonId(personId);
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        String[] images = {base64Image};
        req.setImages(images);

        CreateFaceResponse resp = client.CreateFace(req);
        logger.info("添加人脸成功，人脸ID: {}", resp.getSucFaceIds());
    }


}
